package com.djx.provider.controller;

import com.djx.comm.entity.User;
import com.djx.comm.util.UUIDUtil;
import com.djx.provider.config.executor.ExecutorConfig;
import com.djx.provider.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 多线程控制层
 * @author dingjunxiong
 */
@RestController
@RequestMapping("executor/")
public class TaskExecutorController {
    private static final Logger logger = LoggerFactory.getLogger(TaskExecutorController.class);

    /**
     * 自定义 线程池初始化配置
     */
    @Autowired
    ExecutorConfig executorConfig;

    @Autowired
    UserService userService;


    /**
     * 调用 ExecutorConfig 生成的多线程连接池
     * 无返回值的任务使用execute(Runnable)
     * 有返回值的任务使用submit(Runnable)
     */
    @PostMapping("test1")
    public void test1() {
        for (int i = 0; i < 50; i++) {
            int finalI = i;
            executorConfig.taskExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    message(finalI);
                }
            });
        }
    }

    public void message(int finalI) {
        System.out.println(Thread.currentThread().getName()+" | "+ finalI);
    }

    /**
     * 多线程批量添加用户
     */
    @PostMapping("test2")
    public void test2() {
        for (int i = 1; i <= 100; i++) {
            int finalI = i;
            executorConfig.taskExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    User user = User.builder()
                            .account("张三"+ finalI)
                            .password("123456")
                            .build();
                    user.setId(UUIDUtil.getUUID());
                    user.setStatus(0);
                    try {
                        userService.add(user);
                    } catch (Exception e) {
                        logger.error("添加用户失败：" + user.toString());
                    }
                }
            });
        }

    }

    /**
     * 普通批量添加用户
     */
    @PostMapping("test3")
    public void test3() {
        for (int i = 1; i <= 100; i++) {
            User user = User.builder()
                    .account("李四"+i)
                    .password("123456")
                    .build();
            user.setId(UUIDUtil.getUUID());
            user.setStatus(0);
            try {
                userService.add(user);
            } catch (Exception e) {
                logger.error("添加用户失败：" + user.toString());
            }
        }
    }

}
